<template>
    <el-main v-loading="loading">
        <!-- <el-button @click="downloadAll" :disabled="selectList.length > 0 ? false: true" >download</el-button> -->
        <el-table
            :row-key="getRowKeys"
            :expand-row-keys="expands"
            :data="tableData"
            style="width: 100%"
            table-layout="auto"
            @selection-change="handleSelectionChange"
            @expand-change="handleRowClick"
        >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="fields.srr_title" label="SRR Number"></el-table-column>
            <el-table-column prop="fields.experiment_type" label="Experiment Type"></el-table-column>
            <el-table-column prop="fields.q30" label="Q30"></el-table-column>
            <el-table-column prop="fields.gc_content" label="GC Content"></el-table-column>
            <el-table-column prop="fields.map_ratio" label="Mapping Rate"></el-table-column>
            <el-table-column prop="fields.single" label="Discordantly-mapped Rate"></el-table-column>
            <el-table-column prop="fields.double" label="Concordantly-mapped Rate"></el-table-column>
            <el-table-column type="expand">
                <template #default="props">
                    <div class="expand-container">
                        <div class="expand-card">
                            <el-card>
                                <template #header>
                                    <div class="card-header">
                                        <span class="card-header-title">Cell Detail</span>
                                    </div>
                                </template>
                                <div class="detail-card">
                                    <div v-for="(value, key) of props.row.fields" :key="props.row.pk" class="item-container">
                                        <div class="detail-item">
                                            <div class="item-key">{{ keyIndex[key] }}</div>
                                            <div class="item-value" v-if="keyIndex[key]==='SRR Number'">
                                                {{ value.includes('_') ? value.split('_')[0] : value }}
                                            </div>
                                            <div class="item-value" v-else>
                                                {{ value }}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </el-card>
                        </div>
                        <div class="radar-card">
                            <el-card>
                                <template #header>
                                    <div class="card-header">
                                        <span class="card-header-title">Radar Chart</span>
                                    </div>
                                </template>
                                <div class="detail-card" :ref="refHandler"></div>
                            </el-card>
                        </div>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <div class="pagination">
            <el-pagination
                v-model:current-page="currentPage"
                :page-size="currentPageSize"
                background
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>
    </el-main>
</template>

<script setup lang="ts" name="CellDetail">
    import { useRoute, useRouter } from 'vue-router';
    import { onBeforeMount, ref, reactive } from 'vue'
    import { ElMessage } from 'element-plus'
    import { get, post, } from '@/axios/api';
    import * as echarts from "echarts";
    import { keyIndex } from '../dataConfigs/index'

    let total = ref(0)
    let currentPage = ref(1)
    let currentPageSize = ref(10)
    const route = useRoute()
    let loading = ref(false)
    let selectList = ref<string[]>([])
    let tempData:any = ref(null)    
    let tableData:any = ref([{
        fields: {}
    }])

    let expands: any = ref([]);
    let params = {
        gse_title: route.params.title
    }

    const props = defineProps(['gse', 'sampleType'])

    const getRowKeys = (row:any) => {return row.pk} 

    async function downloadAll() {
        if (selectList.value.length == 0) {
            ElMessage({
                message: 'please select data first',
                type: 'error'
            })
            return
        }
        loading.value = true
        ElMessage({
            message: 'It takes about a few seconds to download data.',
            type: 'info',
        })
        let data = {
            gse_title: route.params.title,
            sample_type: props.sampleType,
            experiment_type: tableData.value[0].fields.experiment_type,
            list: selectList.value
        }

        try {
            let res:any = await post('/download_pkl/', data, {
                responseType: 'blob',
                headers:{ 'Content-Type': 'application/json; application/octet-stream'}
            })
            if (res) {
                const blob = new Blob([res],  { type: 'application/zip' })
                let urlObject = window.URL
                let url = urlObject.createObjectURL(blob)
                let ele = document.createElement("a")
                ele.href = url
                ele.download = "test.zip"
                ele.click()
                urlObject.revokeObjectURL(url)
                loading.value = false
                ElMessage({
                    message: 'data has been downloaded.',
                    type: 'success',
                })
            }
        } catch (error:any) {
            loading.value = false
            ElMessage({
                message: error,
                type: 'error',
            })
        }
    }

    const refHandler = (el:any) => {
        let chart = echarts.init(el, null,{width: 450, height: 600})
        let option = {
            responsive: true,
            legend: {
                data: ['Allocated Budget', 'Actual Spending']
            },
            radar: {
                // shape: 'circle',
                center: ['45%', '50%'],
                radius: '50%',
                startAngle: 130,
                indicator: [
                    {name: 'Short-range', color: 'black',},
                    {name: 'Gini QC', color: 'black'},
                    {name: 'Total contact', color: 'black'},
                    {name: 'Long-range', color: 'black'},
                    {name: 'Cis:trans', color: 'black'},
                    {name: 'Mid-range', color: 'black'},
                    {name: 'Coverage rate', color: 'black'},
                ],
                splitArea: {
                    show: true,
                    areaStyle: {
                        // 使用间隔背景颜色
                        color: ['#f5f5f5', '#ffffff'] // 这里可以设置成你需要的间隔颜色
                    }
                },
                name: {
                    textStyle: {
                        fontSize: 12
                    }
                },
                nameGap: 30
            },
            series: [
                {
                    name: 'basic',
                    type: 'radar',
                    data: [
                        {
                            value: [
                                tempData.value.short,
                                tempData.value.giniQC,
                                tempData.value.mid,
                                tempData.value.long,
                                tempData.value.total,
                                tempData.value.cis_trans,
                                tempData.value.coverage_500kb,
                            ],
                            name: 'basic',
                            label: {
                                show: true,
                                formatter: function (params: {value: any}) {
                                    return params.value;
                                }
                            },
                            areaStyle: {
                                color: '#428BD4',
                            }
                        },
                    ],
                }
            ],
        }
        chart.setOption(option)
    }

    async function getCellData(page: number, page_size: number, params: any) {
        let res:any = {}
        let data = {
            page,
            page_size,
            params
        }
        loading.value = true
        try {
            res = await post('/get_cell_data/', data)
            if (res && res.success) {
                tableData.value = res.list
                currentPage.value = res.page
                total.value = res.total
                loading.value = false
            }
        } catch (error:any) {
            loading.value = false
            ElMessage({
                message: error,
                type: 'error',
            })
        }
    }

    const handleSelectionChange = (val: any) => {
        selectList.value = val
    }


    async function handleSizeChange(val: number) {
        currentPageSize.value = val
        let data = {
            page: currentPage.value,
            page_size: val,
            params
        }
        let res:any = {}
        loading.value = true
        try {
            res = await post('/get_cell_data/', data)
            if (res && res.success) {
                loading.value = false
                tableData.value = res.list
            }
        } catch (error:any) {
            ElMessage({
                message: error,
                type: 'error',
            })
        }
    }

    async function handleCurrentChange(val: number) {
        let data = {
            page: val,
            page_size: currentPageSize.value,
            params
        }
        let res:any = {}
        loading.value = true
        try {
            res = await post('/get_cell_data/', data)
            if (res && res.success) {
                loading.value = false
                currentPage.value = val
                tableData.value = res.list
            }
        } catch (error:any) {
            ElMessage({
                message: error,
                type: 'error',
            })
        }

    }

    function handleRowClick(row: any, expandedRows: any) {
        tempData.value = row.fields
        expands.value = []
        if (expandedRows.length > 0) {
            let pk: String = row.pk
            expands.value.push(pk)
        }

    }

    onBeforeMount(() => {
        let params = {
            gse_title: props.gse,
            sample_type: props.sampleType,
        }
        getCellData(currentPage.value, currentPageSize.value, params)
    })
</script>

<style scoped>
    .pagination {
        margin: 20px 10px;
        display: flex;
        justify-content: center;
    }

    .expand-container {
        width: 100%;
        padding: 10px;
        display: flex;
        justify-content: flex-start;
    }
    .expand-card {
        width: calc(55% - 20px);
        margin-right: 20px;
        height: 700px;
    }
    .radar-card {
        width: calc(45% - 20px);
        margin-right: 20px;
        height: 700px;
    }


    .detail-card {
        width: 100%;
        height: 600px;
        display: flex;
        justify-content: flex-start;
        flex-wrap: wrap;
    }

    .item-container {
        width: calc(33% - 20px);
        margin: 10px;
        display: flex;
        flex-wrap: wrap;
        flex-direction: column;
    }

    .item-key {
        width: 100%;
        margin-bottom: 10px;
        font-family: SourceSansPro;
        font-size: large;
        font-weight: bold;
    }

    .item.value {
        width: 100%
    }

    .card-header-title {
        margin-bottom: 10px;
        font-family: SourceSansPro;
        font-size: large;
        font-weight: bold;  
    }

    .detail-radar-chart {
        width: calc(50% - 10px);
        margin-left: 10px;
        height: 660px;
    }

    .detail-item {
        width: 100%
    }

    .radar-chart-container {
        width: 100%;
        height: 550px;
    }
</style>